package com.lmk.qs.utils;

import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.sql.*;
import java.util.Properties;

    /**
         *JDBC 工具类 连接对象的获取 及资源释放
         * @author 青笙
         * @email  1460961774@qq.com
         */

public class JDBCUtil {

    private static String url;
    private static String user;
    private static String paw;
    private static String driver;
    /**
     * 文件读取只需要一次
     */
    static{

        try {
            Properties pro=new Properties();

            ClassLoader classLoader=JDBCUtil.class.getClassLoader();
           URL src= classLoader.getResource("jdbc.properties");
            String path=src.getPath();


            pro.load(new FileReader(path));
            url=pro.getProperty("url");
            user= pro.getProperty("user");
            paw=pro.getProperty("paw");
            driver=pro.getProperty("driver");
            try {
                Class.forName(driver);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 获取连接方法
     *
     * @return 连接对象
     */
    public static Connection getConnection() throws SQLException {


        return  DriverManager.getConnection(url,user,paw);
    }

    /**
     * 释放资源
     *
     * @param st
     * @param con
     */
    public static void close(Statement st, Connection con) {
        close(null,st,con);


    }

    /**
     * 释放资源
     *
     * @param rs
     * @param st
     * @param con
     */
    public static void close(ResultSet rs, Statement st, Connection con) {
        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (st != null) {
            try {
                st.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }

            }
        if (con != null) {
                try {
                    st.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }

        }
    }
}
